﻿#region Usings

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web.Mvc;
using System.Web.UI;
using EFCachingProvider.Caching;
using Microsoft.Practices.Unity;
using XPressify.ActionFilters;
using XPressify.Data;
using XPressify.Data.CompliedQueries;

#endregion

namespace XPressify.Controllers
{
    [SetCulture]
    public abstract class BaseController : Controller
    {
        [Dependency]
        public IRepository Repository { get; set; }

        
        public XSettings XSettings
        {
            get
            {
                return XSettings.Instance;
            }
        }

        public User CurrentUser
        {
            get
            {
                return Request.IsAuthenticated
                           ? UserCompiledQueries.GetUserByEmail(Repository as Repository, User.Identity.Name)
                           : new User {Id = Guid.Empty, Username = "anonymous"};
            }
        }

        public bool SendTemplatedEmail(List<string> to, string subject, string templatePath, ViewDataDictionary viewData)
        {
            var message = new MailMessage
            {
                Subject = subject,
                IsBodyHtml = true
            };
            foreach (var toAddress in to)
            {
                message.To.Add(new MailAddress(toAddress));
            }
            message.Body = ControlToString(templatePath, viewData);

            try
            {
                var client = new SmtpClient();
                client.Send(message);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        protected string ControlToString(string controlPath, ViewDataDictionary viewData)
        {
            var control = new RazorView(ControllerContext, controlPath, null, false, null);

            var writer = new HtmlTextWriter(new StringWriter());
            control.Render(new ViewContext(ControllerContext, control, viewData, TempData, writer), writer);

            var value = (writer.InnerWriter).ToString();

            return value;
        }

        public ActionResult SetCulture(string id)
        {
            var userCookie = Request.Cookies["Culture"];

            if (userCookie != null)
            {
                userCookie.Value = id;
                userCookie.Expires = DateTime.Now.AddYears(100);
                Response.SetCookie(userCookie);
            }

            return Redirect(Request.UrlReferrer.ToString());
        }

    }
}